package com.example.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.server.mapper.MenuRoleMapper;
import com.example.common.pojo.Admin;
import com.example.common.pojo.Menu;
import com.example.server.mapper.MenuMapper;
import com.example.common.pojo.MenuRole;
import com.example.server.security.context.SecurityContextHolder;
import com.example.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小红
 * @since 2022-09-02
 */
@Service
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private SecurityContextHolder securityContextHolder;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Menu> findMenusByAdminId() {

        //获取当前用户的id
        //匹配对应的用户menu 列表

        Admin userDetails = (Admin) securityContextHolder.getUserDetails();

        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        List<Menu> resultFormRedis = (List<Menu>) operations.get("menu_" + userDetails.getId());
        if (CollectionUtils.isEmpty(resultFormRedis)) {
            log.info("从数据库中访问菜单");
            List<Menu> menusFromDb = menuMapper.findMenusByAdminId(userDetails.getId());
            operations.set("menu_" + userDetails.getId(), menusFromDb,60, TimeUnit.MINUTES);
            return menusFromDb;
        } else {
            log.info("从redis中访问菜单");
            return resultFormRedis;
        }

    }

    @Override
    public List<Menu> findMenusLevel() {
        return menuMapper.findMenusLevel(null);
    }

    @Override
    public List<Integer> findMenuIdsByRid(Integer rid) {
        return menuMapper.findMenuIdsByRid(rid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespBean updateMenuRole(Integer rid, Integer[] mids) {
        /**
         * 1 找到MenuRole 按照rid删除这个角色对应的关系
         * 2 根据mids批量生成该角色所有的和菜单之间的关系
         */
        menuRoleMapper.delete(new QueryWrapper<MenuRole>().eq("rid",rid));

        int result = menuRoleMapper.insertBatch(rid,mids);
        if (result != mids.length) {
            throw RespBean.AUTH_FAILED_ERROR_500.toException();
        }
        return RespBean.success();
    }

}
